import { ITextValuePair } from '../../sys';
import * as SysApi from '../../sys.api';

export enum BookCategory {
    Literature = 1,
    Science = 2,
    History = 3,
}

export const BookCategoryOptions: ITextValuePair[] = [
    { text: '(Literature)', value: BookCategory.Literature },
    { text: '(Science)', value: BookCategory.Science },
    { text: '(History)', value: BookCategory.History },
];

export class Book {
    bookId: number;
    category: BookCategory;
    title: string;
    author: string;
    pubDate: Date;
    price: string;
    amount: number;
    star: boolean;
}

export interface IBookQueryAllCriteria {
    categories?: BookCategory[];
    key?: string;
    minPrice?: number;
    maxPrice?: number;
    minPubDate?: Date;
    maxPubDate?: Date;
}

export interface IBookQueryByIdCriteria {
    bookId: number,
}

export const formatBookCategory = (category: BookCategory): string => {
    switch (category) {
        case BookCategory.Literature:
            return '(Literature)';
        case BookCategory.Science:
            return '(Science)';
        case BookCategory.History:
            return '(History)';
        default:
            return '<Unknown>';
    }
}

export const register = () => {
    SysApi.register('books.queryAll', (params: IBookQueryAllCriteria) => {
        return SysApi.ajaxGet(SysApi.apiUrl('/books'), params);
    });
    SysApi.register('books.queryById', (params: number) => {
        const bookId = params;
        return SysApi.ajaxGet(SysApi.apiUrl('/books/' + bookId));
    })
    SysApi.register('books.save', (params: Book) => {
        const bookId = params.bookId;
        params.bookId = null;
        return SysApi.ajaxPost(SysApi.apiUrl('/books/' + bookId), null, params);
    });
};